﻿using System.Text;
using System.Text.RegularExpressions;

namespace App_Code.Helpers
{
    /// <summary>
    /// Summary description for CuevanaTVExtractor
    /// </summary>
    public class CuevanaTVExtractor
    {
        private const string MOVIE_URL_PATTERN = "http://www.cuevana.tv/player/source?id={0}&subs=,EN&onstart=yes&sub_pre=EN#";
        private const string POST_PARAMETERS = "key={0}&host=megaupload&vars=&id={1}&subs=,ES&tipo=&amp";
        private const string GET_SOURCE_LINK_URL = "http://www.cuevana.tv/player/source_get";

        public static VideoResult ExtractMovieUrl(string moviePageLink)
        {
            var pageContent = Utils.GetPage(moviePageLink, Encoding.UTF8);

            var movieCodeMatch = Regex.Match(pageContent, "<div id=\"videoi\".*?>id=(.+?)&", RegexOptions.Singleline);
            var movieUrl = string.Format(MOVIE_URL_PATTERN, movieCodeMatch.Groups[1].Value);
            
            var movieUrlPageContent = Utils.GetPage(movieUrl, Encoding.UTF8);
            var megauploadMatch = Regex.Match(movieUrlPageContent, "goSource\\('(.+?)','megaupload'", RegexOptions.Singleline);
            var key = megauploadMatch.Groups[1].Value;
            
            var postParams = string.Format(POST_PARAMETERS, key, movieCodeMatch.Groups[1].Value);
            var megaUploadLink = Utils.GetPage(GET_SOURCE_LINK_URL, Encoding.UTF8, string.Empty, postParams);
            //var megaVideoLink = MegaVideoExtractor.ConvertToMegaVideoLink(megaUploadLink);

            //if (megaVideoLink == null)
            //     throw new Exception("Cant extract megaUpload link");

            return MegaVideoExtractor.IsContainVideoLink(megaUploadLink) ?
                MegaVideoExtractor.ExtractMovieUrl(megaUploadLink) : 
                new VideoResult(megaUploadLink, false);
        }

        public static bool IsContainVideoLink(string content)
        {
            return content.ToLower().Contains("cuevana");
        }
    }
}